#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <SDL/SDL.h>

#include "zombies.h"
#include "display.h"
#include "primitives.h"
#include "font.h"
#include "level.h"
#include "items.h"

// image data
#include "items_gfx.h"

// items
item_t items[MAX_ITEMS];
int itemcount;

// sprites surface
SDL_Surface *itemsprites;

// aligned to game item sprites
const char *itemname[]=
{
    "Squirtgun",
    "Fire Ext.",
    "Bubble Gun",
    "Weed Whacker",
    "Golden Key",
    "Sneakers",
    "Monster Potion",
    "Invincible Potion",
    "Mystery Potion",
    "Grey Mystery Potion",
    "Burger",
    "Sodas",
    "Tomato",
    "Popsicle",
    "Banana",
    "Healthkit",
    "Plates",
    "Forks",
    "Cross",
    "Bazooka",
    "Football",
    "Flamethrower",
    "Pandora's Box",
    "Skeleton Key",
    "Clowns",
    "Key Ring",
    "Secret Level",
    "1Up",
    "Coins",
    "Dollars"
};

const char *getitemname(int code)
{
    return itemname[code>>1];
}

void readitems()
{
	unsigned int offset;
	unsigned short next;
	int x;
	
	offset=BASE_PTR+level.item_ptr;

    memset(items,0,sizeof(item_t)*MAX_ITEMS);
    for(x=0;x<MAX_ITEMS;x++)
    {
        next=*(unsigned short *)(romdata+offset);
        if(next==0) break;

        offset+=sizeof(item_t);
    }

    itemcount=x;
    offset=BASE_PTR+level.item_ptr;
    memcpy(&items,romdata+offset,sizeof(item_t)*x);
}

int itemclicked(int x, int y)
{
    int i;

    for(i=0;i<itemcount;i++)
    {
        if(x>items[i].x && x<(items[i].x+16) && y>items[i].y && y<(items[i].y+16))
        {
            return i;
        }
    }

    return -1;
}

void dragitem(int id, int x, int y)
{
    items[id].x+=x;
    items[id].y+=y;
}

void drawitems()
{
    SDL_Rect src,dst;
    unsigned char tile;
    const char *name;
    int i,tx,ty;

    src.w=dst.w=16;
    src.h=dst.h=16;
   
    for(i=0;i<itemcount;i++)
    {
		tile=items[i].code>>1;
		src.x=(tile&0x0f)*16;
		src.y=((tile&0xf0)/16)*16;
        dst.x=items[i].x-bgoffset.x-8;
        dst.y=items[i].y-bgoffset.y-8;

        // let SDL handle clipping
        SDL_BlitSurface(itemsprites,&src,screen,&dst);
        
        name=getitemname(items[i].code);
        
        // center align text on sprite bottom
        tx=items[i].x-bgoffset.x-(strlen(name)*3);
        ty=items[i].y-bgoffset.y+8;
        
        drawtext(name,tx,ty);
    }
}

void inititems()
{
    SDL_Surface *temp;
    SDL_RWops *rw;

    // read bitmap binary stream
    rw=SDL_RWFromConstMem(items_bmp,sizeof(items_bmp));
    temp=SDL_LoadBMP_RW(rw,1); // automatically free RWops
    
    itemsprites=SDL_ConvertSurface(temp,screen->format,SDL_SWSURFACE);
    SDL_FreeSurface(temp);

    // apply color mask
    SDL_SetColorKey(itemsprites,SDL_SRCCOLORKEY|SDL_RLEACCEL,0xff00ff);
}